<script lang="jsx" setup>
import { getCurrentInstance, ref, watch } from 'vue';
import { Input, message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { useAuthStore } from '@/store/modules/auth';
import Modal from '@/components/common/modal.vue';
import { get, post } from '@/service/api/api';
import { isNonNegativeInteger } from '@/utils';
import underReview from '@/assets/imgs/examine-icon/under-review.png';
import unaudited from '@/assets/imgs/examine-icon/unaudited.png';
import audited from '@/assets/imgs/examine-icon/audited.png';

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => false
  },
  operateType: {
    type: String,
    default: 'add'
  },
  rowData: {
    type: Object,
    default: null
  }
});

const instance = getCurrentInstance();
const authStore = useAuthStore();
const emit = defineEmits(['addModalClose', 'addSuccess']);
const modelVisible = ref(props.visible);
const modleAddLoading = ref(false);
const topFormRef = ref(null);
const topFormRef2 = ref(null);
const activeKey = '1';

const topFormList = ref([
  {
    type: 'tabs',
    span: 24,
    name: '基础信息'
  },
  {
    type: 'searchInput',
    key: 'lotId',
    label: 'Lot号',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    disabled: false,
    rule: {
      required: true,
      message: '请输入Lot号',
      trigger: 'change'
    },
    handleSearch() {
      get('/rcerp/agv/erp/findByLotNo', {
        lotNumber: model.value.lotId
      }).then(({ data, error }) => {
        if (!error) {
          Object.keys(model.value).forEach(item => {
            model.value[item] = data[item] || model.value[item];
          });
          model.value.pnlLuo = data.pnlGong;
          model.value.quantity = null;
        }
      });
    }
  },
  {
    type: 'input',
    key: 'moduleNo',
    label: '生产型号',
    span: 8,
    rule: {
      required: true,
      message: '请输入生产型号',
      trigger: 'change'
    },
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'datePicker',
    key: 'modifyTime',
    label: '时间',
    span: 8,
    rule: {
      required: true,
      message: '请选择时间',
      trigger: 'change'
    },
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    showTime: true
  },
  {
    type: 'input',
    key: 'areaTrea',
    label: '表面处理',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'input',
    key: 'thickness',
    label: '板厚',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'input',
    key: 'stackedNum',
    label: '叠板数',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'input',
    key: 'quantity',
    label: '数量',
    span: 8,
    rule: {
      required: true,
      message: '请输入数量',
      trigger: 'change'
    },
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    change() {
      model.value.totalLuo = (model.value.pnlLuo * model.value.quantity).toFixed(3);
    }
  },
  {
    type: 'input',
    key: 'pnlLuo',
    label: 'PNL锣程',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'input',
    key: 'totalLuo',
    label: '总锣程',
    span: 8,
    disabled: true
  },
  {
    type: 'input',
    key: 'runningTime',
    label: '运行时间/趟',
    span: 6,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'input',
    key: 'machineNumber',
    label: '机台编号',
    span: 6,
    rule: {
      required: true,
      message: '请输入机器编号',
      trigger: 'change'
    },
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'input',
    key: 'xCoordinate',
    label: 'X坐标',
    span: 6,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'input',
    key: 'yCoordinate',
    label: 'Y坐标',
    span: 6,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  }
]);

const topFormList2 = ref([
  {
    type: 'radio',
    key: 'checkType1',
    label: '首件检查',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    showReset: true,
    selectOptions: [
      {
        label: 'OK',
        value: 'OK'
      },
      {
        label: 'NG',
        value: 'NG'
      }
    ]
  },

  {
    type: 'radio',
    key: 'checkType2',
    label: '自主检查',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    showReset: true,
    selectOptions: [
      {
        label: 'OK',
        value: 'OK'
      },
      {
        label: 'NG',
        value: 'NG'
      }
    ]
  },

  {
    type: 'radio',
    key: 'checkType3',
    label: '末件检查',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    showReset: true,
    selectOptions: [
      {
        label: 'OK',
        value: 'OK'
      },
      {
        label: 'NG',
        value: 'NG'
      }
    ]
  },

  {
    type: 'input',
    key: 'checkNum1',
    label: '首件检查数量',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'input',
    key: 'checkNum2',
    label: '自主检查数量',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'input',
    key: 'checkNum3',
    label: '末件检查数量',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'radio',
    key: 'shiftType',
    label: '班别',
    span: 8,
    rule: {
      required: true,
      message: '请选择班别',
      trigger: 'blur'
    },
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    selectOptions: [
      {
        label: '白班',
        value: '0'
      },
      {
        label: '夜班',
        value: '1'
      }
    ]
  },
  {
    type: 'textarea',
    key: 'remark',
    label: '备注',
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    textareaRows: 1,
    span: 16
  }
]);

const topFormList3 = ref([
  {
    type: 'tabs',
    span: 24,
    name: '人员信息'
  },

  {
    type: 'input',
    key: 'operator',
    label: '操作员',
    defaultValue: authStore.userInfo.user.nickName || authStore.userInfo.user.userName,
    // disabled: true,
    span: 8
  },
  {
    type: 'input',
    key: 'foreman',
    label: '领班审核',
    disabled: true,
    span: 8
  },
  {
    type: 'input',
    key: 'examiner',
    label: '主管审核',
    disabled: true,
    span: 8
  }
]);

const column = [
  {
    key: 'index',
    dataIndex: 'index',
    title: '序号',
    width: 70,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'badName',
    dataIndex: 'badName',
    title: '检验项目',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'number',
    dataIndex: 'number',
    title: '缺陷数量',
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      if (record.disabled) {
        return <div style="min-width:150px">{record.number}</div>;
      }
      return (
        <Input
          style="height: 22px !important;"
          value={record.number}
          onBlur={e => {
            const value = e.target.value;
            if (!(isNonNegativeInteger(Number(value).toString()) && Number(value >= 0))) {
              message.error('请输入正整数');
              record.number = null;
              return;
            }
            record.number = Number(value);
          }}
        ></Input>
      );
    }
  }
];

const tableData = ref([]);
const scroll = { x: 'auto', y: 'auto' };
const loading = ref(false);

function getTableData() {
  loading.value = true;
  let url;
  if (props.operateType === 'add') {
    url = '/qms/agv/forming/luo/selectBadId';
  } else {
    url = `/qms/agv/forming/luo/listBad?id=${props.rowData.id}`;
  }
  get(url, {})
    .then(({ data, error }) => {
      if (!error) {
        data.forEach((item, index) => {
          item.index = index + 1;
          item.disabled = props.operateType === 'look';
        });

        tableData.value = data;
        console.log('tableData.value :>> ', tableData.value);
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

function getModel(arr) {
  const obj = {};
  arr.forEach(item => {
    obj[item.key] = item.defaultValue || null;
    if (props?.rowData) {
      obj[item.key] = props?.rowData?.[item.key];
    }
    if (item.tansfromDisabled) {
      item.disabled = item.tansfromDisabled(props.operateType);
    }
  });
  return obj;
}

const model = ref(getModel([...topFormList.value, ...topFormList2.value, ...topFormList3.value]));

const addList = ref([{ knifeSize: null, knifeNum: null }]);

function add() {
  addList.value.push({ knifeSize: null, knifeNum: null });
}

function del(index) {
  addList.value.splice(index, 1);
}

async function handleOk(type) {
  const form = { ...topFormRef.value };
  const form2 = { ...topFormRef2.value };
  await form.validateForm();
  await form2.validateForm();
  const params = {
    ...model.value
  };
  const msgObj = {
    add: '新增',
    edit: '修改'
  };
  params.badDoList = tableData.value.filter(item => item.number);
  for (let i = 0; i < addList.value.length; i++) {
    const item = addList.value[i];
    if (item.knifeNum && (item.knifeSize === null || item.knifeSize == 0)) {
      message.error(`刀径${i + 1}不能为空`);
      return;
    }
    if (item.knifeSize && !item.knifeNum) {
      message.error(`刀径数量${i + 1}不能为空`);
      return;
    }
  }
  params.knifes = addList.value.filter(item => item.knifeSize && item.knifeNum);
  let url = '/qms/agv/forming/luo/insert';
  params.time = dayjs(model.value.modifyTime).format('YYYY-MM-DD HH:mm:ss');
  if (props.rowData) {
    params.createTime = model.value.modifyTime;
    params.id = props.rowData.id;
    url = '/qms/agv/forming/luo/update';
    params.state = props.rowData.state;
  }

  delete params.undefined;
  console.log('params :>> ', params);
  modleAddLoading.value = true;
  post(url, params)
    .then(({ error }) => {
      if (!error) {
        message.success(`${msgObj[props.operateType]}成功`);
        const obj = { ...instance.parent.refs.commonSearchRef, ...instance.parent.refs.tableRef };
        obj.formReset();
        obj.tableSelectChange([]);
        handleClose();
      }
    })
    .finally(() => {
      modleAddLoading.value = false;
    });
}

function handleClose() {
  modelVisible.value = false;
  model.value = getModel([...topFormList.value, ...topFormList2.value, ...topFormList3.value]);
  emit('addModalClose');
}

watch(
  () => props.visible,
  val => {
    modelVisible.value = val;
    if (val) {
      [...topFormList.value, ...topFormList2.value, ...topFormList3.value].forEach(item => {
        if (item.tansfromDisabled) {
          item.disabled = item.tansfromDisabled(props.operateType);
        }
      });

      Object.keys(model.value).forEach(item => {
        if (props.rowData) {
          model.value[item] = props.rowData[item];
        } else {
          model.value[item] = null;
        }
      });
      if (props.operateType !== 'add') {
        addList.value = props.rowData.knifes;
      }
      getTableData();
    }
  },
  {
    deep: true,
    immediate: true
  }
);
</script>

<template>
  <Modal
    v-model:visible="modelVisible"
    :title="`${{ add: '新增', edit: '编辑', look: '查看' }[props.operateType]}锣板生产记录表`"
    height="90vh"
    width="70vw"
    :destroy-on-close="true"
    :centered="true"
    @close="handleClose"
  >
    <div class="single-FQC-add-form h-full">
      <div v-if="props.operateType !== 'add'" class="state">
        <template v-if="props.rowData.state === 0">
          <img :src="unaudited" alt="examine-icon" />
        </template>
        <template v-if="props.rowData.state === 2 || props.rowData.state === 4">
          <img :src="underReview" alt="examine-icon" />
        </template>
        <template v-if="props.rowData.state === 3">
          <img :src="audited" alt="examine-icon" />
        </template>
      </div>
      <div class="form w-full">
        <Form ref="topFormRef" v-model:model="model" :form-list="topFormList"></Form>
      </div>
      <div class="add-list w-full">
        <AForm class="my-from w-full" :label-col="{ lg: 8, xs: 4 }" label-wrap>
          <div v-for="(item, index) in addList" :key="index" class="row">
            <div class="w-full flex flex-center gap-15px">
              <div class="input-box flex gap-15px">
                <div class="form-item w-50%">
                  <AFormItem :label="`刀径${index + 1}`" :label-col="{}">
                    <AInput
                      v-model:value="item.knifeSize"
                      size="small"
                      :disabled="props.operateType === 'look'"
                    ></AInput>
                  </AFormItem>
                </div>
                <div class="form-item w-50%">
                  <AFormItem :label="`刀径数量${index + 1}`" :label-col="{}">
                    <AInput
                      v-model:value="item.knifeNum"
                      size="small"
                      :disabled="props.operateType === 'look'"
                    ></AInput>
                  </AFormItem>
                </div>
              </div>
              <div class="btn-box w-150px flex flex-center">
                <AButton type="primary" size="small" :disabled="props.operateType === 'look'" @click="add()">
                  新 增
                </AButton>
                <AButton
                  type="primary"
                  size="small"
                  class="ml-8px"
                  :disabled="props.operateType === 'look'"
                  @click="del(index)"
                >
                  删 除
                </AButton>
              </div>
            </div>
          </div>
        </AForm>
      </div>
      <div class="form w-full">
        <Form ref="topFormRef2" v-model:model="model" :form-list="topFormList2"></Form>
      </div>
      <ATabs v-model:activeKey="activeKey">
        <ATabPane key="1" tab="质量项目"></ATabPane>
      </ATabs>
      <div class="quality-item-table">
        <ATable
          :columns="column"
          :data-source="tableData"
          row-key="badId"
          :pagination="false"
          :scroll="scroll"
          :loading="loading"
          size="small"
          bordered
        ></ATable>
      </div>
      <div class="form w-full">
        <Form ref="topFormRef3" v-model:model="model" :form-list="topFormList3"></Form>
      </div>
    </div>
    <template #footer>
      <div class="modal-footer">
        <AButton v-if="props.operateType == 'add'" type="primary" :loading="modleAddLoading" @click="handleOk('add')">
          保 存
        </AButton>
        <AButton v-if="props.operateType == 'edit'" type="primary" :loading="modleAddLoading" @click="handleOk('edit')">
          修 改
        </AButton>
        <AButton @click="handleClose">关 闭</AButton>
      </div>
    </template>
  </Modal>
</template>

<style lang="scss" scoped>
.single-FQC-add-form {
  border: 1px solid #ccc;
  padding: 0 30px;
  overflow: auto;
  padding-top: 35px;
  position: relative;

  .state {
    position: absolute;
    top: 0;
    right: 100px;
    img {
      height: 80px;
    }
  }

  .add-list {
    .row {
      .input-box {
        width: calc(100% - 165px);
      }
    }

    .my-from {
      :deep(.ant-form-item) {
        margin-bottom: 5px;
      }
    }
  }
}
</style>
